<?php
namespace app\admin\controller;
use think\Db;
use think\Cookie;
use think\Cache;

class Rule extends Common
{
    public function index()
    {

     $data =  Db::name('rule')->where('is_show',1)->paginate(10);
     $parent =  Db::name('rule')->select();
     $this->assign('parent',$parent);
     $this->assign('data',$data);
     return $this->fetch();

    }

    //软删除
    public function del(){
    	//获取的是一个数组
        //读取cookie
      $id = Cookie::get('id');
      //删除缓存
      Cache::rm('user_'.$id);
    	$ids = input('post.ids/a');
    	//将数组转为字符串 以逗号分隔
    	$ids = implode(',',$ids);
    	//软删除 更新状态
    	$result = Db::name('rule')->where("id in ($ids)")->setField('is_show',0);
    	if($result){
    		$this->success("删除成功");
    	}else{
    		$this->error("删除失败");
    	}
    }
    public function addRule(){
         //读取cookie
          $id = Cookie::get('id');
          //删除缓存
          Cache::rm('user_'.$id);
		$data = input('post.data/a');
        
		// $data = input('get.');
    	// dump($data);die;
		// $parent_id = Db::name('rule')->select();
		// dump($parent_id);die;
		// $this->assign('data',$parent_id);


		if(!$data){
	    	return json(array('code'=>0,'msg'=>"参数错误"));
	    }

	    if (!$data["rule_name"] or !$data["module_name"] or !$data["controller_name"] or !$data["action_name"]) {
	    	return json(array('code'=>0,'msg'=>"请将添加信息填写完整"));
	    }

		$result = model('Rule')->addRule($data);
         
		// dump($rule_id);die;
		if($result){
			return json(['code'=>1,'msg'=>'添加成功']);
    	}else{
			return json(['code'=>0,'msg'=>'添加失败']);
    	}
    		
    }
    public function edit($id=''){
    	if (request()->isPost()) {
             //读取cookie
              $id = Cookie::get('id');
              //删除缓存
              Cache::rm('user_'.$id);
    		$data = input('post.data/a');
			// dump($data);die;
			$result = Db::name('rule')->where('id',$data['id'])->update(['rule_name'=>$data['rule_name'],'module_name'=>$data['module_name'],'controller_name'=>$data['controller_name'],'action_name'=>$data['action_name'],'parent_id'=>$data['parent_id'],'is_show'=>$data['is_show']]);

			if ($result) {
    		 		return json(['code'=>1,'msg'=>'修改成功']);
    		 }else{
	    			return json(['code'=>0,'msg'=>'修改失败']);
	    	 }
	    	 
    	}else{
    		// dump($id);die;
    		$rule = model('Rule')->editRule($id);
			// dump($rule);die;
    		$this->assign('rule',$rule);
    		// dump($rule);die;
    		$parent =  Db::name('rule')->select();
     		$this->assign('parent',$parent);
    		return $this->fetch();
    	}
    


    
    }
}
